package XML与JSON.使用DOM4J;

//import java.io.File;
import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

public class DOM4J查询xml {

   public static void main(String[] args) {

      try {
      	SAXReader reader = new SAXReader();
      	//InputStream input=DOM4J查询xml.class.getResourceAsStream("input.txt");//默认是从此类所在的包下取资源
      	InputStream input=DOM4J查询xml.class.getClassLoader().getResourceAsStream("XML与JSON\\使用DOM4J\\input.txt");//默认是从ClassPath根下获取资源
      	Document document = reader.read( input);
         //File inputFile = new File("input.txt");
         //Document document = reader.read( inputFile);

         System.out.println("Root element :" + document.getRootElement().getName());

         Element classElement = document.getRootElement();

         List<Node> nodes = document.selectNodes("/class/student[@rollno = '493']" );//查询属性为rollno="493"的student
         System.out.println("----------------------------");
         
         for (Node node : nodes) {
            System.out.println("\nCurrent Element :"+ node.getName());
            System.out.println("Student roll no : "+ node.valueOf("@rollno") );
            System.out.println("First Name : "+ node.selectSingleNode("firstname").getText());
            System.out.println("Last Name : "+ node.selectSingleNode("lastname").getText());
            System.out.println("First Name : "+ node.selectSingleNode("nickname").getText());
            System.out.println("Marks : "+ node.selectSingleNode("marks").getText());
         }
      } catch (DocumentException e) {
         e.printStackTrace();
      }
   }
}
/*
这将产生以下结果 −

Root element :class
----------------------------
Current Element :student
Student roll no : 493
First Name : Vaneet
Last Name : Gupta
First Name : vinni
Marks : 95
*/